<template>
    <view class="container">
        <view class="main">
            <view class="custom-cell">
                <text class="cell-label">发货人</text>
                <view class="cell-main"
                    ><input class="cell-input" type="text" v-model="data.ContactName" placeholder="请填写发货人"
                /></view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">联系电话</text>
                <view class="cell-main">
                    <input class="cell-input" type="number" v-model="data.ContactTel" placeholder="请填写联系电话" />
                </view>
            </view>
            <view class="custom-cell">
                <text class="cell-label">发货地址</text>
                <view class="cell-main" @click="areaSelectFn">
                    <text class="cell-value">{{ regionName }}</text>
                    <uni-icons type="arrowright"></uni-icons>
                </view>
            </view>
            <view class="custom-cell">
                <textarea
                    class="cell-textarea"
                    placeholder="请填写详细地址(街道、楼牌号等)"
                    v-model="data.ContactAddress"></textarea>
                <uni-icons class="icon-location" type="location-filled" size="48" @click="getLoaction"></uni-icons>
            </view>
        </view>
        <view class="card-cell">
            <text class="cell-label">设为默认地址</text>
            <switch
                class="cell-switch"
                :color="easyGetColor()"
                :checked="data.IsDefault"
                @change="change('checked', $event.detail.value)" />
        </view>
        <view class="action-bar">
            <text class="btn btn-success" @click="save">保存地址</text>
            <text class="btn btn-gray" v-if="isEidt" @click="del">删除地址</text>
        </view>
        <uni-popup ref="pick" type="dialog">
            <uni-popup-dialog
                type="text"
                title="温馨提示"
                content="确定删除该地址?"
                :before-close="true"
                @close="close"
                @confirm="doDel"></uni-popup-dialog>
        </uni-popup>
        <uni-popup ref="areaSelect" type="bottom" background-color="#fff" :safe-area="false">
            <area-select :address-data="data" @pickArea="pickArea"></area-select>
        </uni-popup>
    </view>
</template>

<script>
import searchBar from "@/components/common/search-bar.vue"
import areaSelect from "@/uni-sub-base/components/area-select/area-select.vue"
import { userAddressAddOrEdit, userAddressDelete } from "@/service/api/member.js"
import { mapbatchSmartParse, UpdateUserAddress, DeleteUserAddress } from "@/pages_supplier/service/api/supplier.js"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"

export default {
    components: {
        searchBar,
        areaSelect,
    },
    data() {
        return {
            placeholderText: "搜索已有地址",
            searchKey: "",
            data: {
                AddressName: "",
                ContactName: "",
                ContactTel: "",
                ContactAddress: "",
                IsDefault: false,
                ProvinceId: 0,
                ProvinceName: "",
                CityId: 0,
                CityName: "",
                AreaId: 0,
                AreaName: "",
                StreetId: 0,
                StreetName: "",
                Longitude: "",
                Latitude: "",
                ZipCode: null,
            },
            isEidt: false,
            regionName: "请选择省、市、区",
        }
    },
    onLoad(e) {
        if (e.data) {
            this.data = JSON.parse(decodeURIComponent(e.data))

            this.isEidt = true
            this.getRegionName()
        } else {
            uni.setNavigationBarTitle({
                title: "新增地址",
            })
        }
    },
    mounted() {},
    methods: {
        //设置默认地址
        change(name, value) {
            this.data.isDefault = value
        },
        //保存
        save() {
            //必填值校验
            if (this.data.ContactName.trim() == "") {
                this.easyToast("请填写发货人")
                return
            }
            if (this.data.ContactTel.trim() == "") {
                this.easyToast("请填写联系电话")
                return
            }
            if (this.data.ContactTel.length < 11) {
                this.easyToast("请正确填写联系电话")
                return
            }
            if (this.data.ContactAddress.trim() == "") {
                this.easyToast("请填写详细地址")
                return
            }
            if (!this.data.Longitude || !this.data.Latitude) {
                this.easyToast("请先定位地址")
                return
            }
            UpdateUserAddress(this.data).then((res) => {
                if (res.State == 1) {
                    this.easyToast("提交成功")
                    setTimeout(() => {
                        this.easyGoBack()
                    }, 500)
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        //删除
        del() {
            this.$refs.pick.open()
        },
        //取消
        close() {
            this.$refs.pick.close()
        },
        //确认删除
        doDel() {
            this.close()
            let path = "?addressId=" + this.data.ID
            DeleteUserAddress(path).then((res) => {
                if (res.State == 1) {
                    this.easyToast("删除成功")
                    setTimeout(() => {
                        this.easyGoBack()
                    }, 500)
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        //选择地区
        areaSelectFn() {
            this.$refs.areaSelect.open()
        },
        //选择地区回调
        pickArea(data) {
            this.$refs.areaSelect.close()
            this.data = Object.assign(this.data, data)
            this.getRegionName()
        },
        getRegionName() {
            let line = "-"
            this.regionName = `${this.data.ProvinceName || ""}-${this.data.CityName || ""}${
                this.data.AreaName ? line + this.data.AreaName : ""
            }${this.data.StreetName ? line + this.data.StreetName : ""}`
            // this.data.ProvinceName?this.data.ProvinceName:'' +
            // this.data.CityName?"-"+this.data.CityName:''+
            // this.data.AreaName?"-"+this.data.AreaName:''+
            // this.data.StreetName?"-"+this.data.StreetName:''
        },
        getLoaction() {
            //#ifdef MP-WEIXIN
            this.getCenterLocation()
            //#endif
            //#ifdef APP
            uni.navigateTo({
                url: "/pages/map/map-poi",
                events: {
                    getSelectData: (data) => {
                        this.getAppP(data)
                        console.log(data)
                        this.data.ContactAddress = data.address.replace(/\\/g, "")
                        this.data.Longitude = data.location.longitude
                        this.data.Latitude = data.location.latitude
                    },
                },
            })
            //#endif
            //#ifdef H5
            getLocation(
                (res) => {
                    if (res) {
                        this.data.ContactAddress = res.address.street + res.address.streetNum

                        this.getP(res.address)
                    }
                },
                (err) => {
                    console.log(err)
                },
            )
            //#endif
        },
        getCenterLocation() {
            var that = this
            wx.authorize({
                scope: "scope.userLocation",
                complete: function (res) {
                    wx.chooseLocation({
                        success(str) {
                            var key = "V7DBZ-K7C22-SXXUJ-CDUE7-AM2LH-AEFCM"
                            //发送请求通过经纬度反查地址信息
                            var getAddressUrl =
                                "https://apis.map.qq.com/ws/geocoder/v1/?location=" +
                                str.latitude +
                                "," +
                                str.longitude +
                                "&key=" +
                                key +
                                "&get_poi=1"
                            wx.request({
                                url: getAddressUrl,
                                success: function (result) {
                                    console.log(result)
                                    var province = result.data.result.address_component.province
                                    var city = result.data.result.address_component.city
                                    var district = result.data.result.address_component.district
                                    var address = result.data.result.formatted_addresses.recommend

                                    that.data.ContactAddress =
                                        result.data.result.address_component.street_number + address
                                    that.data.Longitude = str.longitude
                                    that.data.Latitude = str.latitude
                                    that.getmapP(result.data.result.address_component)
                                },
                            })
                        },
                    })
                },
            })
        },
        getP(res) {
            let item = {
                ContactAddress: res.street + res.streetNum,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreeName: res.street,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getAppP(res) {
            let item = {
                ContactAddress: res.address,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getmapP(res) {
            let item = {
                ContactAddress: res.street_number,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreeName: res.street,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        //智能识别
        batchSmartParse(param) {
            mapbatchSmartParse(param).then((res) => {
                if (res.Data && res.Data.list && res.Data.list.length > 0) {
                    let result = res.Data.list[0]
                    console.log(result)
                    this.data.ProvinceId = result.ProvinceId
                    this.data.ProvinceName = result.ProvinceName
                    this.data.CityId = result.CityId
                    this.data.CityName = result.CityName
                    this.data.AreaId = result.AreaId
                    this.data.AreaName = result.AreaName
                    this.data.StreetId = 0
                    this.data.StreetName = ""
                    this.getRegionName()
                }
            })
        },
    },
}
</script>

<style lang="scss">
.container {
    padding: $app-page-padding;
}

.main {
    margin-bottom: 40rpx;
    background: $color-white;
    border-radius: $border-radius-10;
}

.action-bar {
    display: flex;
    flex-direction: column;

    .btn {
        margin-left: 0;
        margin-bottom: 20rpx;
        height: 80rpx;
        font-size: 32rpx;
    }
}

.custom-cell {
    display: flex;
    flex-direction: row;
    align-items: center;
    min-height: 66rpx;
    padding: $app-page-padding;
    border-bottom: solid 1rpx $uni-bg-color-grey;

    &:last-child {
        border-bottom: 0;
    }

    .cell-label {
        display: flex;
        flex: 1;
    }

    .cell-main {
        display: flex;
        flex: 3;
        overflow: hidden;

        .cell-value {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: $app-color-text-desc;
            font-size: $font-size-28;
        }

        .cell-input {
            color: $app-color-text-desc;
            font-size: $font-size-28;
        }
    }

    .cell-textarea {
        height: 160rpx;
        color: $app-color-text-desc;
        font-size: $font-size-28;
    }

    .icon-location {
        padding: $app-page-padding;
        margin-right: -$app-page-padding;
    }
}

.card-cell {
    margin-bottom: 40rpx;
}

.cell-switch {
    transform: scale(0.8);
}
</style>
